package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuQuery;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 */
@Slf4j
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;


    //@Autowired
    //private StringRedisTemplate stringRedisTemplate; //适合 key和value都是字符串类型

    @Autowired
    private RedisTemplate redisTemplate; //适合值是任意类型



    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    //原子性
    @Override
    public int insertProduct(Product product) {
        //1.保存Product对象到product表
        productMapper.insert(product); //主键回填

        //2.保存List<ProductSku>对象到product_sku表
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(product.getId());
            productSkuMapper.insert(productSku);

            //添加商品库存  //3.保存List<SkuStock>对象到sku_stock表
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        //4.保存ProductDetails对象到product_details表
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetails.setProductId(product.getId());
        productDetailsMapper.insert(productDetails);

        return 1;
    }


    @Override
    public Product selectProductById(Long id) {
        //1.根据id查询Product对象
        Product product = productMapper.selectById(id);

        //2.封装扩展字段：查询商品对应多个List<ProductSku>
        //select * from product_sku where product_id =?
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<Long> productSkuIdList = productSkuList.stream().map(productSku -> productSku.getId()).toList();


        // select * from sku_stock where sku_id in (1,2,3,4,5,6)
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        Map<Long, Integer> skuIdToTatalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(productSku -> {
            //返回ProductSku对象，携带了库存数据；
            productSku.setStockNum(skuIdToTatalNumMap.get(productSku.getId()));
        });

        product.setProductSkuList(productSkuList);

        //3.封装扩展字段：商品详情图片List<String>
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        String imageUrls = productDetails.getImageUrls();   //url,url,url
        String[] urls = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.asList(urls));
        //返回Product对象
        return product;
    }


    @Override
    public int updateProduct(Product product) {
        //1.更新Product
        productMapper.updateById(product);

        //2.更新SKU   List<ProductSku>
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        productSkuList.forEach(productSku -> {
            productSkuMapper.updateById(productSku);

            //3.更新库存   List<ProductSku> -> 获取扩展字段stockNum
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        });

        //4.更新详情ProductDetails
        ProductDetails productDetails = productDetailsMapper
                .selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);

        return 1;
    }


    @Override
    public int deleteProductByIds(Long[] ids) {
        //1.删除Product表数据
        // delete from product where id in (1,2)
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //2.删除ProductSku表数据
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, Arrays.asList(ids)));
        List<Long> productSkuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(productSkuIdList);

        //3.删除SkuStock表数据
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        //4.删除ProductDetails表数据
        // delete from product_details where product_id in (1,2)
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, Arrays.asList(ids)));
        return 1;
    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批拒绝");
        }
        productMapper.updateById(product);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        // 同步商品上下架状态至数据库和Redis位图，通过位图高效管理SKU存在性，解决缓存穿透问题
        String dataKey ="sku:product:data";//bitmap数据的key
        Product product = new Product();
        product.setId(id);//指定更新的是哪个商品
        if (status == 1) {
            product.setStatus(1);//1代表上架

            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>()
                    .eq(ProductSku::getProductId, id));
            /*
            ProductSku::getProductId 是 Lambda 方法引用，表示要查询的字段是 ProductSku 实体中通过 getProductId() 方法获取的字段
             */
            for (ProductSku productSku:productSkuList){
                redisTemplate.opsForValue().setBit(dataKey,productSku.getId(),true);
            }
        } else {
            product.setStatus(-1);//-1代表下架
            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>()
                    .eq(ProductSku::getProductId, id));
            for (ProductSku productSku:productSkuList){
                redisTemplate.opsForValue().setBit(dataKey,productSku.getId(),false);
            }

        }
        productMapper.updateById(product);
    }


    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.getTopSale();
    }


    @Override
    public List<ProductSku> skuList(SkuQuery skuQuery) {
        return productSkuMapper.skuList(skuQuery);
    }


    /**
     * 服务提供者：6个接口来服务于商品详情查询。需要进行优化，提供查询效率。
     * 需要使用redis来提高性能。
     */

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            //先从缓存获取
            //业务数据Key 形式：前缀+业务唯一标识
            //构造 Redis 缓存的 Key，格式为 product:sku{skuId}，确保每个商品 SKU 的缓存唯一,避免key冲突
            String dataKey="product:sku"+skuId;
            //查询Redis获取业务数据
            //声明一个 ProductSku 类型的变量 productSku，并将其初始化为 null
            ProductSku productSku=null;
            if (redisTemplate.hasKey(dataKey)){
                //从 Redis 获取缓存的 ProductSku 对象
                productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                log.info("从redis获取数据-productSku:"+productSku);
                return productSku;
            }
            //缓存区没有再从数据库获取,取完放在缓存中,为下次使用做准备
            //分布式锁避免缓存击穿
            //构造分布式锁的 Key 和唯一值
            String lockKey="lock:key:product:sku:"+skuId;
            //使用 UUID 生成唯一值，确保锁释放时不会误删其他线程的锁并且移除所有连字符
            String lockValue=UUID.randomUUID().toString().replaceAll("-","");
            //锁的过期时间会比业务时间长一些
            Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);
            if (ifAbsent){
                //分布式锁,加锁成功
                try {
                    productSku=getProductSkuFromDB(skuId);//查询不存在,也放到缓存中,在一定程度上解决同一个key不存在缓存穿透问题
                    int timeOut=productSku==null?1:10;
                    redisTemplate.opsForValue().set(dataKey,productSku,timeOut,TimeUnit.MINUTES);
                    return productSku;
                } finally {
                    //释放锁
                    //通过LUA脚本保证原子性删除锁
                    String script = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                            "then\n" +
                            "   return redis.call('del',KEYS[1])\n" +
                            "else\n" +
                            "   return 0\n" +
                            "end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script);
                    redisScript.setResultType(Long.class);
                    Long result = (Long)redisTemplate.execute(redisScript, Arrays.asList(lockKey),lockValue);
                }
            }else{
                //加锁失败
                try {
                    Thread.sleep(100);//比数据库查询时间稍微长一点就行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return this.getProductSku(skuId);//自旋
            }
        } catch (Exception e) {
            //异常处理时直接查询数据库，确保服务可用性
            return this.getProductSkuFromDB(skuId);
        }
    }
    public ProductSku getProductSkuFromDB(Long skuId) {
        return productSkuMapper.selectById(skuId);
    }



    @Override
    public Product getProduct(Long id) {
        return productMapper.selectById(id);
    }


    @Override
    public SkuPrice getSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice));
        SkuPrice skuPrice = new SkuPrice();
        BeanUtils.copyProperties(productSku, skuPrice);
        return skuPrice;
    }


    @Override
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
    }


    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id).select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }


    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }


    // select * from product_sku where id in (1,2,3)
    // select id,sale_price,market_price from product_sku where id in (1,2,3)
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        if (CollectionUtils.isEmpty(skuIdList)) {
            return new ArrayList<SkuPrice>();
        }
        List<ProductSku> skuList = productSkuMapper
                .selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList)
                        .select(ProductSku::getId, ProductSku::getSalePrice, ProductSku::getMarketPrice));
        if (CollectionUtils.isEmpty(skuList)) {
            return new ArrayList<SkuPrice>();
        }
        return skuList.stream().map((sku) -> {
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(sku.getId());
            skuPrice.setSalePrice(sku.getSalePrice());
            skuPrice.setMarketPrice(sku.getMarketPrice());
            return skuPrice;
        }).toList();
    }

    //代码可以优化两次循环可以变成一次
    @Transactional
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        //第一步:去重 (openfeign远程调用可能开启重试机制,所以需要去重--用分布式锁setnx)
        String key = "sku:checkAndLock:" + orderNo;//分布式锁
        String dataKey = "sku:lock:data:" + orderNo;//缓存锁定数据的key

        //作用: 只有当指定的 key 不存在时，才会设置该 key 的值
        //别名: setIfAbsent()通常也称为 SETNX (SET if Not eXists)
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, 1, 1, TimeUnit.HOURS);//获取分布式锁
        if (!ifAbsent){
            if (redisTemplate.hasKey(dataKey)){//如果有这个key,说明t1线程已经走到第三步,把锁的库存存在了redis里
                //所以这个地方我们就不需要干活了
                return "";//锁库存成功,没有消息就是好消息
            }else {
               //此时表示,t1线程正在干活,还没存在redis中
                return "重复提交";//拿不到锁去重,ifAbsent是false,!ifAbsent是true
                //加入来了两个线程t1 t2,第一个t1是true 取非 false,往下走
                //t2来了,key value这个锁已经上了,拿不到锁,false !之后true 告你你是重复提交
            }
        }

        //第二步:检查库存
        /*
        -- 检查库存 5是购买的商品数量
        select * from sku_stock where sku_id=1 and 5<=available_num for update 加了行锁
        */
        for (SkuLockVo skuLockVo : skuLockVoList) {
            //得到的是一个对象
            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (skuStock==null){
                //库存不够
                skuLockVo.setIsHaveStock(false);
            }else {
                //查到了,库存够
                skuLockVo.setIsHaveStock(true);
            }
        }

        //第三步:锁库存,存储数据到Redis中
        if (skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.getIsHaveStock())) {//存在没有库存的情况---组合消息
            StringBuilder builder = new StringBuilder();
            skuLockVoList.stream().filter(skuLockVo -> !skuLockVo.getIsHaveStock()).forEach(skuLockVo -> {
                builder.append("商品[" + skuLockVo.getSkuId() + "]库存不足;");
            });
            if (StringUtils.hasText(builder.toString())) {//有字符串,则证明库存不足
                redisTemplate.delete(key);//需要删除分布式锁,因为可能重试的时候,有人解锁库存或者商家修改了库存
                return builder.toString();
            }
        }else{
            //库存都够---锁库存
            for (SkuLockVo skuLockVo : skuLockVoList) {
                /*
                -- 锁定库存 也就是说你现在要买5件商品 lock_num就得锁5件,available_num就得减5件
                -- lock_num=lock_num+5(原来的值+要锁定的值)
                -- available_num=available_num-5
                update sku_stock set lock_num=lock_num+5,available_num=available_num-5 where sku_id=1
                */
                int lock = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
                if (lock==0){
                    redisTemplate.delete(key);//删除分布式锁
                    throw new ServiceException("锁库存失败");
                }
            }
        }

        //锁定库存后,需要将库存保存到redis中,以便后续解锁库存(延迟消息--未支付或者用户手动取消)或减库存(支付成功(30分钟内))
        redisTemplate.opsForValue().set(dataKey,skuLockVoList);//不加超时时间,解锁库存或减库存之后会帮我进行
        return "";//锁库存成功
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlock(String orderNo) {
        //1.去重  (异步消息幂等处理)
        String key = "sku:unlock:" + orderNo; //分布式锁
        String dataKey = "sku:lock:data:" + orderNo;  //缓存锁定数据的key
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, 1, 1, TimeUnit.HOURS);
        if(!ifAbsent){
            return; //重复消息直接结束了
        }

        //获取到分布式锁
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if(CollectionUtils.isEmpty(skuLockVoList)){
            return;
        }
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if(row==0){
                redisTemplate.delete(key);
                throw new ServiceException("解锁失败");
            }
        }

        //解锁后立即删除缓存。避免重复解锁库存或减库存
        redisTemplate.delete(dataKey);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void minus(String orderNo) {
        //1.去重  (异步消息幂等处理)
        String key = "sku:minus:" + orderNo; //分布式锁
        String dataKey = "sku:lock:data:" + orderNo;  //缓存锁定数据的key
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, 1, 1, TimeUnit.HOURS);
        if(!ifAbsent){
            return; //重复消息直接结束了
        }

        //获取到分布式锁
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if(CollectionUtils.isEmpty(skuLockVoList)){
            return;
        }
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if(row==0){
                redisTemplate.delete(key);
                throw new ServiceException("减库存失败");
            }
        }

        //解锁后立即删除缓存。避免重复解锁库存或减库存
        redisTemplate.delete(dataKey);
    }
}